import React, { useState, useEffect } from 'react';
import './textPage.css';
import Header from '../Header/Header';
import ApiService from '../../api/index';
import cycbjtImg from '../../assets/login/cycbjt.png';
import shdyjImg from '../../assets/login/shdyj.png';
import iconBackImg from '../../assets/icon/icon-back.png';

// 行李图片
import hshsImg from '../../assets/icon/hshs.png';
import myflImg from '../../assets/icon/myfl.png';
import jzjlImg from '../../assets/icon/jzjl.png';
import szjxImg from '../../assets/icon/szjx.png';
import jyczImg from '../../assets/icon/jycz.png';
import hwylImg from '../../assets/icon/hwyl.png';
import jbaxImg from '../../assets/icon/jbax.png';
import thggImg from '../../assets/icon/thgg.png';
import ylghImg from '../../assets/icon/ylgh.png';
import plrsImg from '../../assets/icon/plrs.png';
import nnyyImg from '../../assets/icon/nnyy.png';
/**
 * TextPage 页面组件类
 * 功能：显示文本内容页面
 * 参数：onBack - 返回上一页的回调函数
 * 返回值：JSX元素
 */
const TextPage = ({ onBack, onGoToRankPage }) => {
    // 行李图片数组
    const luggageImages = [
        { img: hshsImg, text: '***' },
        { img: myflImg, text: '***' },
        { img: jzjlImg, text: '***' },
        { img: szjxImg, text: '***' },
        { img: jyczImg, text: '***' },
        { img: hwylImg, text: '***' },
        { img: jbaxImg, text: '***' },
        { img: thggImg, text: '***' },
        { img: ylghImg, text: '***' },
        { img: plrsImg, text: '***' },
        { img: nnyyImg, text: '***' }
    ];

    // 随机选择5个行李图片
    const [displayItems, setDisplayItems] = useState([]);
    // 默契度数据状态
    const [matchData, setMatchData] = useState(null);
    const [matchScore, setMatchScore] = useState(80); // 默认值

    useEffect(() => {
        const getRandomItems = () => {
            const shuffled = [...luggageImages].sort(() => 0.5 - Math.random());
            return shuffled.slice(0, 5); // 固定选择5个
        };

        setDisplayItems(getRandomItems());

        // 调用默契度展示接口
        fetchMatchScore();
    }, []);

    /**
     * 获取默契度展示数据
     */
    const fetchMatchScore = async () => {
        try {
            // 从localStorage获取openId和userId
            const openId = localStorage.getItem('openId');
            const userId = localStorage.getItem('userId');

            console.log('获取默契度数据 - openId:', openId, 'userId:', userId);

            if (openId && userId) {
                const response = await ApiService.ranking.displayingRanking({
                    openId: openId,
                    userId: userId
                });

                console.log('默契度展示接口响应:', response);

                if (response.length > 0) {
                    setMatchScore(response[0].matchScore);
                    setMatchData(response[0]);
                    console.log('设置默契度得分:', response[0].matchScore);
                    console.log('猜测的物品数据:', response[0].guessInfo);
                    console.log('原始物品数据:', response[0].baggageInfo);
                }
            } else {
                console.log('缺少openId或userId，无法调用默契度展示接口');
            }
        } catch (error) {
            console.error('获取默契度数据失败:', error);
        }
    };
    /**
     * 返回按钮点击处理函数
     * 功能：返回上一页
     * 参数：无
     * 返回值：无
     */
    const handleBackClick = () => {
        if (onBack) {
            onBack();
        }
    };

    /**
     * 跳转到排行榜页面的处理函数
     * 功能：跳转到rankpage
     * 参数：无
     * 返回值：无
     */
    const handleGoToRankPage = () => {
        if (onGoToRankPage) {
            onGoToRankPage();
        }
    };

    return (
        <div className="text-page" style={{ backgroundImage: `url(${cycbjtImg})` }}>
            <div className="text-page-content">
                <Header />

                <img src={shdyjImg} alt="背景" className='text-bg' />


                <div className='text-tip'>
                    <div className='text-tip-percent'>{matchScore}%</div>
                    <div className='text-tip-text-nht'>你和TA的默契度</div>
                </div>

                <div className='text-tip-text'>
                    <div className='text-you-guess'>
                        <div className='text-you-guess-text-styles'>你猜的</div>
                        <div>
                            {/* 已选择的行李展示区域 */}
                            <div className="package-items-grid">
                                {(matchData?.guessInfo || displayItems).map((item, index) => (
                                    <div
                                        key={index}
                                        className="package-item"
                                        style={{
                                            backgroundImage: `url(${iconBackImg})`
                                        }}
                                    >
                                        <div
                                            className="package-item-icon"
                                            style={{
                                                backgroundImage: `url(${item.picurl || item.img})`
                                            }}
                                        ></div>
                                        <div className="package-item-text">
                                            {item.name || item.text}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    <div className='text-ta-guess-line'></div>

                    <div className='text-you-guess-text'>
                        <div className='text-ta-guess-text-styles'>TA选的</div>
                        <div>
                            {/* 他选的 */}
                            <div className="package-items-grid">
                                {(matchData?.baggageInfo || displayItems).map((item, index) => (
                                    <div
                                        key={index}
                                        className="package-item"
                                        style={{
                                            backgroundImage: `url(${iconBackImg})`
                                        }}
                                    >
                                        <div
                                            className="package-item-icon"
                                            style={{
                                                backgroundImage: `url(${item.picurl || item.img})`
                                            }}
                                        ></div>
                                        <div className="package-item-text">
                                            {item.name || item.text}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
                <div className='text-btn'>
                    <div className='text-btn-text'>我也要测</div>
                    <div className='text-btn-rangk' onClick={handleGoToRankPage} style={{ cursor: 'pointer' }}>默契度排名</div>
                </div>
            </div>
        </div>
    );
};

export default TextPage;